﻿using System;
using System.Diagnostics;
using System.Threading;

namespace msilgc.driver.cuda {
    internal sealed class ProcessOutputReader : IDisposable {
        private readonly Process _proc;
        private Thread _stdout;
        private Thread _stderr;
        private volatile string _stdoutStr;
        private volatile string _stderrStr;

        public ProcessOutputReader(Process proc) {
            _proc = proc;
            _stdout = new Thread(ReadStdout);
            _stderr = new Thread(ReadStderr);
            _stdout.Start();
            _stderr.Start();
        }

        private void ReadStderr() {
            _stderrStr = _proc.StandardError.ReadToEnd();
        }

        private void ReadStdout() {
            _stdoutStr = _proc.StandardOutput.ReadToEnd();
        }

        public string GetOutput() {
            WaitForCompletion();
            return string.Concat(_stderrStr, _stdoutStr);
        }

        private void WaitForCompletion() {
            if (_stdout != null) {
                _stdout.Join();
                _stdout = null;
            }
            if (_stderr != null) {
                _stderr.Join();
                _stderr = null;
            }
        }

        public void Dispose() {
            WaitForCompletion();
        }
    }
}
